package com.java.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.java.service.OssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFile(InputStream inputStream, String module, String filename) {
        String url = null;
        try {
            //获取实例
            String endpoint = "oss-cn-beijing.aliyuncs.com";
            String accessKeyId = "LTAI5tSCVtEhNBhBXz6Wwsza";
            String accessKeySecret = "1B4zibwRaBEhFlz4znXt7YQMADA5zZ";
            String bucketName = "src-oss-yang";
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 判断存储空间examplebucket是否存在。如果返回值为true，则存储空间存在，否则存储空间不存在。
            if (!ossClient.doesBucketExist("src-oss-yang")) {
                ossClient.createBucket("src-oss-yang");
                // 设置存储空间的访问权限为私有。
                ossClient.setBucketAcl("src-oss-yang", CannedAccessControlList.PublicRead);
            }

            filename = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
            String key = module + new DateTime().toString("/yyyy/MM/dd/") + filename;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream);

            ossClient.putObject(putObjectRequest);
            url = "http://" + "src-oss-yang" + "." + "oss-cn-beijing.aliyuncs.com" + "/" + key;
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    //删除文件
    @Override
    public void remove(String url) {
        //获取实例
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI5tSCVtEhNBhBXz6Wwsza";
        String accessKeySecret = "1B4zibwRaBEhFlz4znXt7YQMADA5zZ";
        String bucketName = "src-oss-yang";


        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        String objectName = url.replace("http://" + "src-oss-yang" + "." + "oss-cn-beijing.aliyuncs.com" + "/","");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
